package com.tuanbiao.presenter.auth;

import android.text.TextUtils;
import android.view.KeyEvent;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.hzjq.data.callback.OnResultCallback;
import com.hzjq.data.hzjq.entity.CapRecordEntity;
import com.hzjq.data.minbao.entity.AuthEntity;
import com.hzjq.lib.BlastKool;
import com.hzjq.lib.bean.PlanInfo;
import com.hzjq.lib.cap.bean.ReadResult;
import com.hzjq.lib.cap.read.ReadCapLoader;
import com.hzjq.lib.cap.scan.Scanner;
import com.tuanbiao.R;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.constants.Constants;
import com.tuanbiao.controllers.AuthController;
import com.tuanbiao.data.callback.OnBaseResultCallback;
import com.tuanbiao.keyevent.KeyEventHelper;
import com.tuanbiao.transformers.SchedulerTransformer;
import com.tuanbiao.utils.AuthLgComparator;
import com.tuanbiao.utils.LibCollections;
import com.tuanbiao.utils.MediaUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/4/25 10:40
 */
public class AuthOfflinePresenter extends BasePresenter<AuthController.Model, AuthController.OfflineView> implements AuthController.OfflinePresenter {

    //是否启用扫描头
    private boolean mIsScanner = true;
    private ReadCapLoader readCapLoader;
    private Scanner scanCapLoader;
    private int repeatCount = 0;
    private ArrayList<CapRecordEntity> repeatCaps = new ArrayList<>();
    //是否正在扫描雷管
    private boolean isScanCap;

    public AuthOfflinePresenter(AuthController.Model model, AuthController.OfflineView rootView) {
        super(model, rootView);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void init() {
        readCapLoader = BlastKool.Companion.loader().read();
        scanCapLoader = BlastKool.Companion.loader().scan();
        scanCapLoader.setTabScanModeKeysCallback(KeyEventHelper.getInstance().getScanModeKeys(), b -> {
            Timber.i(TAG + "#setTabScanModeKeysCallback:" + b);
            mRootView.onScannerTypeChange(b);
        });
        isScanCap = true;
        scanCapLoader.close();
        scanCapLoader.open("", scanResult -> {
            Timber.i(TAG + "#scanCapSingle#result:" + scanResult.getStatus() + ",msg:" + scanResult.getMsg());
            isScanCap = false;
            if (scanResult.getStatus() == Constants.CodeErrorCode.SUCCESS) {
                MediaUtils.playSound(R.raw.sound);
            } else if (scanResult.getStatus() == Constants.CodeErrorCode.REPEAT) {
                MediaUtils.playSound(R.raw.repeat_scan);
                mRootView.showScanRepeat(null, scanResult);
            } else if (scanResult.getStatus() == Constants.CodeErrorCode.CODE_ERROR) {
                MediaUtils.playSound(R.raw.code_error);
            } else if (scanResult.getStatus() == Constants.CodeErrorCode.NO_PLAN_ID_SUCCESS) {
                Timber.i(TAG + "#scanCapSingle#result:" + scanResult.getStatus() + ",msg:" + scanResult.getMsg());
                menuInsertDetonator(getUidFromMsg(scanResult.getMsg()));
            }
        });
    }

    private String getUidFromMsg(String msg) {
        return msg;
    }

    @Override
    public void menuReadOnline(int count) {
        if (!checkReadOrScan(count)) {
            return;
        }
        repeatCount = 0;
        readCapLoader.read("", () -> {
            readCapLoader.onDestroy();
        }, new OnResultCallback<ReadResult>() {
            @Override
            public void onResult(ReadResult readResult) {
                Timber.i("readOnline:" + readResult.isReadEnd());
                Timber.i("readOnline#repeatCaps:" + LibCollections.size(readResult.getRepeatCaps()));
                if (!LibCollections.isEmpty(readResult.getRepeatCaps())) {
                    repeatCount += LibCollections.size(readResult.getRepeatCaps());
                }
                if (readResult.isReadEnd() && repeatCount > 0) {
                    mRootView.showRepeatDialog(repeatCount);
                }
//                mRootView.addDetonators(readResult.getNewCaps());
                if (readResult.isReadEnd()) {
                    if (readResult.getInfo().getUidErrorCount() > 0) {
                        MediaUtils.playSound(R.raw.code_error);
                        mRootView.showUidError(readResult.getInfo().getUidErrorCount());
                    }
                    PlanInfo planInfo = readResult.getInfo();
                    mRootView.showStatistics(planInfo);
                    Timber.i("onResult#readResult:" + readResult.getInfo());
                }
            }

            @Override
            public void onFailed(@NonNull String s) {
                mRootView.showMessage(s);
                Timber.i("onResult#onFailed:" + s);
            }
        });
    }

    @Override
    public void menuInsertDetonator(String uid) {
        AuthEntity.Lgs.Lg entity = createDetonator(uid);
        Timber.i(TAG + "#insertDetonator:" + entity);
        mRootView.addDetonators(entity);
        mRootView.scrollToPosition(uid);
    }

    @Override
    public void menuInsertDetonator(String startUid, String endUid) {
        List<AuthEntity.Lgs.Lg> entities = createDetonators(startUid, endUid);
        mRootView.addDetonators(entities);
    }

    private List<AuthEntity.Lgs.Lg> createDetonators(String startUid, String endUid) {
        Timber.i("createDetonators#startUid:" + startUid + ",endUid:" + endUid);
        String pre = startUid.substring(0, 11);
        String start = startUid.substring(11);
        String end = endUid.substring(11);
        Timber.i("createDetonators#pre" + pre + ",start:" + start + ",end:" + end);
        int startIndex = Integer.parseInt(start);
        int endIndex = Integer.parseInt(end);
        List<AuthEntity.Lgs.Lg> uids = new ArrayList<>(endIndex - startIndex);
        for (int i = startIndex; i <= endIndex; i++) {
            if (i<10) {
                uids.add(createDetonator(pre + "0"+i));
            }else {
                uids.add(createDetonator(pre + i));
            }

        }
        Timber.i("createDetonators:" + uids);
        return uids;
    }

    private AuthEntity.Lgs.Lg createDetonator(String uid) {
        AuthEntity.Lgs.Lg entity = new AuthEntity.Lgs.Lg();
        if(uid.length() == 27){
            entity.setUid(uid.substring(14));
        } else {
            entity.setUid(uid);
        }
        return entity;
    }

    @Override
    public long getMaxDelay() {
        return mModel.getMaxDelay();
    }

    @Override
    public void downloadAuthFile(List<AuthEntity.Lgs.Lg> lgs) {
        List<String> uids = createUidList(lgs);
        Timber.i("downloadAuthFile#" + uids);
        mModel.authOffline(uids, new OnBaseResultCallback<AuthEntity>() {
            @Override
            public void onSuccess(AuthEntity entity) {
                Timber.i("authOffline:" + entity.toString());
                if(mRootView == null) return;
                mRootView.showMessage("授权成功");
                if (null != entity.getLgs()) {
                    setItems(entity);
                }
            }

            @Override
            public void onFailed(String msg) {
                if(mRootView == null) return;
                mRootView.showMessage("下载授权文件失败，请检查后重试！");
            }
        });
    }

    @Override
    public void downloadAuthFile(String code, String startCode, String count) {
        if (TextUtils.isEmpty(code)) {
            mRootView.showMessage(R.string.auth_offline_hint_code);
            return;
        }
        if (code.length() != 11) {
            mRootView.showMessage("请输入11位发编号");
            return;
        }
        if (TextUtils.isEmpty(startCode)) {
            mRootView.showMessage(R.string.auth_offline_hint_start_code);
            return;
        }
        if (!TextUtils.isDigitsOnly(startCode)) {
            mRootView.showMessage("起始编号只能输入整数");
            return;
        }
        if (Integer.parseInt(startCode) > 99) {
            mRootView.showMessage("起始编号不能大于99");
            return;
        }

        if (TextUtils.isEmpty(count)) {
            mRootView.showMessage(R.string.auth_offline_hint_count);
            return;
        }
        if (!TextUtils.isDigitsOnly(count)) {
            mRootView.showMessage("雷管数量只能输入整数");
            return;
        }
        if (Integer.parseInt(count) > 100) {
            mRootView.showMessage("发数量不能大于100");
            return;
        }
        int countInt = Integer.parseInt(count);
        int start = Integer.parseInt(startCode);
        mModel.authOffline(createUidList(code, countInt, start), new OnBaseResultCallback<AuthEntity>() {
            @Override
            public void onSuccess(AuthEntity entity) {
                Timber.i("authOffline:" + entity.toString());
                mRootView.showMessage("授权成功");
                if (null != entity.getLgs()) {
                   setItems(entity);
                }
            }

            @Override
            public void onFailed(String msg) {
                mRootView.showMessage("下载授权文件失败，请检查后重试！");
            }
        });
    }

    private void setItems(AuthEntity entity) {
        addDispose(Observable.create((ObservableOnSubscribe<List<AuthEntity.Lgs.Lg>>) emitter -> {
            ArrayList<AuthEntity.Lgs.Lg> lgs = entity.getLgs().getLg();
            Collections.sort(lgs, new AuthLgComparator());
            emitter.onNext(lgs);
        }).compose(new SchedulerTransformer<>())
                .subscribe(lgs -> mRootView.setItems(lgs)));

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return scanCapLoader.dispatchKeyEvent(event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        scanCapLoader.stop();
        scanCapLoader.close();
        readCapLoader.onDestroy();
    }

    private List<String> createUidList(String code, int count, int startCode) {
        int size = count + startCode > 100 ? 100 - startCode : count;
        List<String> uidList = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            int end = startCode + i;
            if (end < 10) {
                uidList.add(code + "0" + end);
            } else {
                uidList.add(code + end);
            }
        }
        Timber.i("createUidList:" + uidList);
        return uidList;
    }

    private List<String> createUidList(List<AuthEntity.Lgs.Lg> lgs) {
        List<String> uids = new ArrayList<>();
        for (AuthEntity.Lgs.Lg lg : lgs) {
            uids.add(lg.getUid());
        }
        return uids;
    }

    private boolean checkReadOrScan(int count) {
//        if (count >= BlastLoader.Companion.getMaxSupportPlanCapSize()) {
//            mRootView.showMessage("已达到组网的最大雷管数据，无法再导入雷管数据");
//        }
//        if (null == currentProject) {
//            mRootView.showMessage("未绑定项目");
//            return false;
//        }
//        if (TextUtils.isEmpty(mPlantStr)) {
//            mRootView.showMessage("未选择方案");
//            return false;
//        }
        if (isScanCap) {
            mRootView.showMessage("正在扫描雷管信息");
        }
        return true;
    }
}
